package com.ttbj.product.api.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ttbj.core.util.DtoTransitionUtils;
import com.ttbj.owner.bean.po.Owner;
import com.ttbj.owner.component.OwnerCache;
import com.ttbj.owner.dao.OwnerMapper;
import com.ttbj.product.api.OwnerFacade;
import com.ttbj.product.bean.dto.OwnerDto;
import com.ttbj.util.Assert;
import com.ttbj.util.ResultUtil;

@Service("ownerFacade")
public class OwnerFacadeImpl implements OwnerFacade {

	@Autowired
	private OwnerCache ownerCache = null;

	@Autowired
	private OwnerMapper ownerMapper = null;

	@Override
	public Long addOwner(String openId, OwnerDto dto) throws Exception {
		Assert.assertFiledJsr(dto); // 参数验证
		Owner owner = (Owner) DtoTransitionUtils.trans(Owner.class, dto.insTime().openId(openId).no());
		int code = ownerMapper.insertSelective(owner);// 数据添加入数据库
		ownerCache.setValueByCache(openId, dto.id(owner.getOwnerId()), dto.getOwnerIsSender()); // 缓存处理
		return owner.getOwnerId();
	}

	@Override
	public List<OwnerDto> allOwner(String openId, Integer isSender) throws Exception {
		List<OwnerDto> list = ownerCache.getListByCache(openId, isSender);
		if (null == list || list.isEmpty()) {
			list = ownerMapper.getOwner(new OwnerDto(isSender, openId));
		}
		return list;
	}

	@Override
	public void delOwner(String openId, Long id, Integer isSender) throws Exception {
		Owner owner = new Owner();
		owner.setOwnerId(id);
		owner.setOwnerIsDelete(0);
		if (0 == ownerMapper.updateByPrimaryKeySelective(owner)) {
			ResultUtil.throwExcepion(ResultUtil.createFail("messages", 212), "删除寄件人或收件人信息出错、原因：修改isDelete出错修改的信息不存在");
		}
		ownerCache.delValueByCache(openId, id, isSender);
	}

	@Override
	public OwnerDto getOwner(String openId, Long id, Integer isSender) {
		OwnerDto dto = null;
		if (openId != null) {
			dto = ownerCache.getValueByCache(openId, isSender, id);
		}
		if(dto == null){
			Owner owner = ownerMapper.selectByPrimaryKey(id);
			if (null != owner) {
				Integer ownerIsSender = owner.getOwnerIsSender();
				if (ownerIsSender != null && ownerIsSender.equals(isSender)) {
					dto = (OwnerDto) DtoTransitionUtils.trans(OwnerDto.class, owner);
				}
			}
		}
		return dto;
	}

}
